package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.annotation.RepeatForm;
import com.example.demo.common.enums.CustomizeEnum;
import com.example.demo.common.handler.CustomException;
import com.example.demo.entity.Question;
import com.example.demo.entity.dto.FileDTO;
import com.example.demo.service.impl.QuestionServiceImpl;
import com.example.demo.service.utils.MinioTemplate;
import com.example.demo.service.utils.UploadPicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author: ak
 * @Date: 2020/3/31 23:50
 */
@Controller
public class UtilsController {
    @Autowired
    QuestionServiceImpl questionService;
    @Autowired
    UploadPicService uploadPicService;
    @Autowired
    MinioTemplate minioTemplate;

    @PostMapping("imgUpload")
    public String imgUpload(MultipartFile img) {
        uploadPicService.imgUpload(img);
        return "index";
    }

    @ResponseBody
    @PostMapping("markdownImgUpload")
    public FileDTO imgUpload(@RequestParam(value = "editormd-image-file") MultipartFile file,
                             HttpServletResponse response) throws MalformedURLException, CustomException {
        URL url = null;
        try {
            url = new URL(minioTemplate.upload(file));
            FileDTO fileDTO = new FileDTO();
            fileDTO.setSuccess(1);
            fileDTO.setUrl(url);
            fileDTO.setMessage("成功");
            return fileDTO;
        } catch (CustomException e) {
            throw new CustomException(CustomizeEnum.IMG_ERROR);
        }
    }

    @GetMapping("forumPage")
    public String forumPage(Integer pageIndex, HttpServletRequest request) {
        Page<Question> pageService = questionService.getQuestionList(pageIndex, 10);
        if (pageIndex > pageService.getSize() || pageIndex < 1) {
            request.setAttribute("errorMsg", "后面没了，别点了!");
            return "forward:1/forum";
        }
        request.setAttribute("questionList", pageService.getRecords());
        request.setAttribute("curPage", pageIndex);
        if (pageService.hasNext()) {
            request.setAttribute("nextPage", "");
        }
        if (pageService.hasPrevious()) {
            request.setAttribute("prePage", "");
        }
        request.setAttribute("lastPage", pageService.getSize());
        return "forum";
    }

}
